package com.css.fxfzdzzh.modules.basicData.landslideSite.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzdzzh.base.annotation.EntityValue;
import com.css.fxfzdzzh.base.attachment.entity.Attachment;
import com.css.fxfzdzzh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzdzzh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzdzzh.base.exception.ShpFieldException;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.common.utils.LocationUtil;
import com.css.fxfzdzzh.constants.FxfzConstants;
import com.css.fxfzdzzh.constants.RedisKeyConstants;
import com.css.fxfzdzzh.constants.YNEnum;
import com.css.fxfzdzzh.modules.basicData.entity.SensingImage;
import com.css.fxfzdzzh.modules.basicData.landslideSite.entity.FieldDesc;
import com.css.fxfzdzzh.modules.basicData.landslideSite.entity.LandslideSiteFileData;
import com.css.fxfzdzzh.modules.basicData.landslideSite.entity.LandslideSiteMetaData;
import com.css.fxfzdzzh.modules.basicData.landslideSite.entity.LandslideSiteVersion;
import com.css.fxfzdzzh.modules.basicData.landslideSite.entity.param.DataVersionPageParam;
import com.css.fxfzdzzh.modules.basicData.landslideSite.repository.LandslideSiteRepository;
import com.css.fxfzdzzh.modules.basicData.landslideSite.service.LandslideSiteService;
import com.css.fxfzdzzh.modules.basicData.landslideSite.vo.*;
import com.css.fxfzdzzh.modules.basicData.param.SysDataVersionSameTypeDataExistParam;
import com.css.fxfzdzzh.modules.basicData.repository.impl.SensingImageRepository;
import com.css.fxfzdzzh.modules.eqLandslide.lawAnalysis.vo.SlopesVO;
import com.css.fxfzdzzh.modules.evaluate.VO.VersionPageVO;
import com.css.fxfzdzzh.modules.evaluate.entity.SoftSoilDrill;
import com.css.fxfzdzzh.modules.evaluate.repository.SoftSoilRepository;
import com.css.fxfzdzzh.modules.sandLiquefaction.entity.SandLiquefactionDrill;
import com.css.fxfzdzzh.modules.sandLiquefaction.repository.SandLiquefactionRepository;
import com.css.fxfzdzzh.modules.surfaceRupture.entity.SurfaceRupture;
import com.css.fxfzdzzh.modules.surfaceRupture.repository.SurfaceRuptureRepository;
import com.css.fxfzdzzh.util.*;
import com.css.fxfzdzzh.util.fileParsing.ParsingResult;
import com.css.fxfzdzzh.util.fileParsing.shp.ShpAnalyticUtil;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.zcpt.sys.entity.SUser;
import com.css.fxfzdzzh.zcpt.sys.entity.vo.MhjArea;
import com.css.fxfzdzzh.zcpt.sys.service.SUserService;
import com.css.fxfzdzzh.zcpt.sys.service.SysAreaService;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.gson.internal.LinkedTreeMap;
import org.apache.commons.lang3.StringUtils;
import org.hsqldb.rights.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2023年02月22日  13:57
 */
@Service
public class LandslideSiteServiceImpl implements LandslideSiteService {

    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Resource
    LandslideSiteRepository landslideSiteRepository;

    @Resource
    SensingImageRepository sensingImageRepository;

    @Resource
    SurfaceRuptureRepository surfaceRuptureRepository;

    @Resource
    SUserService sUserService;

    @Resource
    AttachmentInfoService attachmentInfoService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SysAreaService sysAreaService;

    @Resource
    SandLiquefactionRepository sandLiquefactionRepository;

    @Resource
    SoftSoilRepository softSoilRepository;


    public final static String DATA_VERSION_CODE_PREFIX = "JC";
    public static final String DATA_FROM = "HPXCDC";

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Value("${image.localDir}")
    private String localDir;

    @Resource
    @Qualifier("myTaskExecutor")
    private Executor executor;

    @Override
    public Map<String, Object> page(DataVersionPageParam dataVersionPageParam) {
        Map<String, Object> map = landslideSiteRepository.page(dataVersionPageParam);
        List<LandslideSiteVersion> list =(List<LandslideSiteVersion>) map.get("rows");
        List<LandslideSiteVO> voList = new ArrayList<>(list.size());
        if(PlatformObjectUtils.isNotEmpty(list)){
            list.forEach(entity->{
                LandslideSiteVO vo = new LandslideSiteVO();
                BeanUtils.copyProperties(entity,vo);
                fileIdTransformEntity(entity,vo);
                vo.setUploadUser(entity.getUploadUserName());
                voList.add(vo);
            });
        }
        map.put("rows", voList);
        return map;
    }
    private void fileIdTransformEntity(LandslideSiteVersion entity, LandslideSiteVO vo){
        getAttachFileEntity(entity,vo);
        getDataFileEntity(entity,vo);
    }
    /**
     * 获取附件文件信息
     */
    private void getAttachFileEntity(LandslideSiteVersion entity, LandslideSiteVO vo){
        List<Attachment> attachFileList = getFileEntity(entity.getAttachmentIds());
        vo.setAttachmentFileList(attachFileList);
    }
    /**
     * 获取数据文件信息
     */
    private void getDataFileEntity(LandslideSiteVersion entity, LandslideSiteVO vo){
        List<Attachment> dataFileList = getFileEntity(entity.getDataFileIds());
        vo.setDataFileList(dataFileList);
    }
    private List<Attachment> getFileEntity(String fileIds){
        if(StringUtils.isNotBlank(fileIds)){
            String[] dataIds = fileIds.split(",");
            List<Attachment> attachList = new ArrayList<>(dataIds.length);
            for (String dataFileId : dataIds) {
                AttachmentInfoEntity attach = attachmentInfoService.getAttach(dataFileId);
                if (PlatformObjectUtils.isNotEmpty(attach)) {
                    Attachment attachmentFile = new Attachment();
                    attachmentFile.setId(attach.getAttachId());
                    attachmentFile.setName(attach.getAttachName());
                    attachList.add(attachmentFile);
                }
            }
            return attachList;
        }
        return new ArrayList<>(0);
    }

    @Override
    public String getVersionCode(String dataLevel) {
        return getVersionCodeByDataLevel(dataLevel);
    }

    /**
     * 生成版本号
     *
     * @param dataLevel 所选的数据级别
     * @return
     */
    private String getVersionCodeByDataLevel(String dataLevel) {
        String dataVersionCodeSerialNumber = stringRedisTemplate.opsForValue().get(RedisKeyConstants.DATA_VERSION_CODE_SERIAL_NUMBER_KEY);
        if (StringUtils.isBlank(dataVersionCodeSerialNumber)) {
            dataVersionCodeSerialNumber = "001";
        } else {
            StringBuilder stringBuilder = new StringBuilder();
            String t = String.valueOf(Integer.parseInt(dataVersionCodeSerialNumber) + 1);
            for (int i = t.length(); i < 3; i++) {
                stringBuilder.append("0");
            }
            dataVersionCodeSerialNumber = stringBuilder.append(t).toString();
        }
        stringRedisTemplate.opsForValue().set(RedisKeyConstants.DATA_VERSION_CODE_SERIAL_NUMBER_KEY, dataVersionCodeSerialNumber);
        stringRedisTemplate.expireAt(RedisKeyConstants.DATA_VERSION_CODE_SERIAL_NUMBER_KEY, Date.from(LocalDateTime.of(LocalDate.now(), LocalTime.MAX).toInstant(ZoneOffset.of("+8"))));
        return DATA_VERSION_CODE_PREFIX + "0" + dataLevel + DATA_FROM + DateUtil.format(new Date(), "yyyyMMdd") + dataVersionCodeSerialNumber;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String saveNewVersion(LandslideSiteVersion landslideSite) {
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        landslideSite.setDdvId(IdUtil.getSnowflakeNextIdStr())
        .setUploadTime(PlatformDateUtils.getCurrentTimestamp()).setUploadUser(PlatformSessionContext.getUserID()).setUploadUserName(sUser.getUserName())
        .setCreateTime(new Date()).setCreateUser(PlatformSessionContext.getUserID()).setDataRangeStr(this.buildDataRange(landslideSite)).setDelFlag(YNEnum.N.toString());
        landslideSiteRepository.save(landslideSite);
        return landslideSite.getVersionCode();
    }

//    @Override
//    public void saveMetaDataInfo(LandslideSiteFileData metaData) {
//        String userId = PlatformSessionContext.getUserID();
//        String user = sUserService.getSUser(userId);
//        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
//        metaData.setCreateTime(new Date()).setCreateUser(userId).setCreateUserName(sUser.getUserName()).
//                setDvmdId(UUIDGenerator.getUUID());
//        landslideSiteRepository.saveMetaDataInfo(metaData);
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String overWriteOldVersion(LandslideSiteVersion sysDataVersion) {
        //删除被替换的旧的版本信息
        landslideSiteRepository.delVersionDataByVersionCode(sysDataVersion.getVersionCode(),PlatformSessionContext.getUserID());
        //删除旧的版本关联的数据
        landslideSiteRepository.delOldVersionData(sysDataVersion.getVersionCode());
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        sysDataVersion.
                setDdvId(IdUtil.getSnowflakeNextIdStr()).
                setUploadTime(PlatformDateUtils.getCurrentTimestamp()).
                setUploadUser(PlatformSessionContext.getUserID()).
                setUploadUserName(sUser.getUserName()).
                setDataRangeStr(this.buildDataRange(sysDataVersion)).
                setCreateTime(new Date()).
                setCreateUser(PlatformSessionContext.getUserID());
        landslideSiteRepository.save(sysDataVersion);
        return sysDataVersion.getVersionCode();
    }

    /**
     * 构建数据范围文字显示
     *
     * @param sysDataVersion 查询接口查询参数，数据版本原实体
     */
    private String buildDataRange(LandslideSiteVersion sysDataVersion) {
        StringBuilder stringBuilder = new StringBuilder();
        String prefix = sysDataVersion.getDataRangeCountry() == 1 ? "国家级" : "省级";
        if (StringUtils.isNotBlank(sysDataVersion.getDataRangeProvince())) {
            String provinceName = sysAreaService.getAreaNameByAreaIdFromCache(sysDataVersion.getDataRangeProvince()); // 省
            if (StringUtils.isNotBlank(sysDataVersion.getDataRangeCity()) && !"全部".equals(sysDataVersion.getDataRangeCity())) {
                String cityName = sysAreaService.getAreaNameByAreaIdFromCache(sysDataVersion.getDataRangeCity()); // 市
                if (StringUtils.isNotBlank(sysDataVersion.getDataRangeArea())) {
                    String areaName = sysAreaService.getAreaNameByAreaIdFromCache(sysDataVersion.getDataRangeArea()); // 区县
                    stringBuilder.append(prefix).append("（").append(provinceName).append(cityName).append(areaName).append("）");
                } else {
                    stringBuilder.append(prefix).append("（").append(provinceName).append(cityName).append("）");
                }
            } else {
                stringBuilder.append(prefix).append("（").append(provinceName).append("）");
            }
        } else {
            stringBuilder.append(prefix);
        }
        return stringBuilder.toString();
    }

    @Override
    public VersionMetaDataInfoVO getVersionMetaDataInfo(String versionCode) {
        VersionMetaDataInfoVO vo = new VersionMetaDataInfoVO();
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        LandslideSiteVersion landslideSiteVersion = landslideSiteRepository.getVersionInfo(versionCode);
        vo.setDataRangeCountry(landslideSiteVersion.getDataRangeCountry()).setDataRangeProvince(landslideSiteVersion.getDataRangeProvince())
                .setDataRangeCity("全部".equals(landslideSiteVersion.getDataRangeCity())?"":landslideSiteVersion.getDataRangeCity()).setDataRangeArea(landslideSiteVersion.getDataRangeArea());
        LandslideSiteMetaData landslideSiteMetaData = landslideSiteRepository.getVersionMetaDataInfo(versionCode);
        if(PlatformObjectUtils.isEmpty(landslideSiteMetaData.getUploadTime())){
            landslideSiteMetaData.setUploadTime(new Date());
        }
        if(PlatformObjectUtils.isEmpty(landslideSiteMetaData.getUploadUserName())){
            landslideSiteMetaData.setUploadUserName(sUser.getUserName());
        }
        if(PlatformObjectUtils.isEmpty(landslideSiteMetaData.getUploadUser())){
            landslideSiteMetaData.setUploadUser(PlatformSessionContext.getUserID());
        }
        if(PlatformObjectUtils.isNotEmpty(landslideSiteMetaData.getFieldNum())){
            landslideSiteMetaData.setFieldNum(landslideSiteMetaData.getFieldNum().trim());
        }
        if(PlatformObjectUtils.isNotEmpty(landslideSiteMetaData.getFieldEntry())){
            landslideSiteMetaData.setFieldEntry(landslideSiteMetaData.getFieldEntry().trim());
        }
        landslideSiteMetaData.setIsSpatialData(Integer.parseInt(YNEnum.N.toString()));
        landslideSiteMetaData.setSpatialDataType("");
        landslideSiteMetaData.setDataRangeCountry(landslideSiteVersion.getDataRangeCountry()+"");
        landslideSiteMetaData.setDataRangeProvince(landslideSiteVersion.getDataRangeProvince());
        landslideSiteMetaData.setDataRangeCity(landslideSiteVersion.getDataRangeCity());
        landslideSiteMetaData.setDataRangeArea(landslideSiteVersion.getDataRangeArea());
        //获取字段个数和数据条目用于页面展示
//        Integer num = getUploadFileFieldNum();
        landslideSiteMetaData.setFieldNum(landslideSiteMetaData.getFieldNum());
        //获取导入的数据条数
//        Integer uploadFileNum = landslideSiteRepository.getUploadFileNum(versionCode);
        landslideSiteMetaData.setFieldEntry(landslideSiteMetaData.getFieldEntry());
        landslideSiteMetaData.setVersionCode(versionCode);
        vo.setLandslideSiteMetaData(landslideSiteMetaData);
        return vo;
    }

    private Integer getUploadFileFieldNum() {
        Field[] declaredFields = LandslideSiteFileData.class.getDeclaredFields();
        AtomicInteger integer = new AtomicInteger(0);
        if(declaredFields.length>0){
            for(Field field : declaredFields){
                field.setAccessible(true);
                EntityValue entityValue = field.getAnnotation(EntityValue.class);
                if(entityValue==null){
                    continue;
                }
                integer.getAndAdd(1);
            }
        }
        return integer.get();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMetaDataInfo(LandslideSiteMetaData metaData) {
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        metaData.setDvmdId(UUIDGenerator.getUUID());
        metaData.setDelFlag(YNEnum.N.toString());
        metaData.setUploadUser(PlatformSessionContext.getUserID());
        metaData.setUploadUserName(sUser.getUserName());
        metaData.setUploadTime(new Date());
        if("".equals(metaData.getVersionCode())){
            metaData.setVersionCode("JC01HPXCDC20230524010");
        }
        landslideSiteRepository.saveMetaDataInfo(metaData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMetaDataInfo(LandslideSiteMetaData metaData) throws Exception{
        String userID = PlatformSessionContext.getUserID();
        LandslideSiteVersion versionInfo = landslideSiteRepository.getVersionInfo(metaData.getVersionCode());
        if(!userID.equals(versionInfo.getCreateUser())){
            throw new RuntimeException("修改失败,只能修改自己上传的数据");
        }
        if(StringUtils.isBlank(metaData.getDvmdId())){
            //表示该数据版本没有生成过元数据信息则新增元数据信息
            this.saveMetaDataInfo(metaData);
        }else{
            String userId = PlatformSessionContext.getUserID();
            metaData.setUpdateUser(userId);
            landslideSiteRepository.updateMetaDataInfo(metaData);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<String> codeList) throws Exception{
        String userID = PlatformSessionContext.getUserID();
        codeList.forEach(versionCode->{
            LandslideSiteVersion versionInfo = landslideSiteRepository.getVersionInfo(versionCode);
            if(!userID.equals(versionInfo.getCreateUser())){
                throw new RuntimeException("删除失败,只能上传本人新增的数据");
            }
            //先删除元数据信息
            landslideSiteRepository.deleteMetaData(versionCode,PlatformSessionContext.getUserID());
            //删除解析的数据信息
            landslideSiteRepository.deleteData(versionCode,PlatformSessionContext.getUserID());
            //删除版本信息
            landslideSiteRepository.deleteVersionData(versionCode,PlatformSessionContext.getUserID());
        });
    }

    @Override
    public void parseShp(String fileIds,String versionCode) throws Exception{
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        //不管这个版本是否上传过数据，都先处理关联的数据
        landslideSiteRepository.updateData(versionCode);
        AttachmentInfoEntity attach = attachmentInfoService.getAttach(fileIds);
        File file = new File(attach.getFileDirId()+File.separator+attach.getAttachPath());
        List<LandslideSiteFileData> stratumData = FileUtil2.importExcel(new FileInputStream(file),0,1, LandslideSiteFileData.class);
        for(int i = 0 ; i<stratumData.size();i++){
            stratumData.get(i).setGeom("POINT("+stratumData.get(i).getLongitude().toString()+" " +stratumData.get(i).getLatitude().toString()+")");
            stratumData.get(i).setDvmdId(UUIDGenerator.getUUID());
            stratumData.get(i).setVersionCode(versionCode);
            stratumData.get(i).setCreateTime(new Date());
            stratumData.get(i).setCreateUser(PlatformSessionContext.getUserID());
            stratumData.get(i).setCreateUserName(sUser.getUserName());
            stratumData.get(i).setDelFlag(YNEnum.N.toString());
            String landslideType = stratumData.get(i).getLandslideType();
            if(PlatformObjectUtils.isNotEmpty(landslideType)){
                if("牵引式滑坡".equals(landslideType)){
                    landslideType = "1";
                }else if("推移式滑坡".equals(landslideType)){
                    landslideType = "2";
                }else if("混合式滑坡".equals(landslideType)){
                    landslideType = "3";
                }
            }
            stratumData.get(i).setLandslideType(landslideType);
            @NotBlank(message = "滑坡性质不能为空") String landslideShape = stratumData.get(i).getLandslideShape();
            if(PlatformObjectUtils.isNotEmpty(landslideShape)){
                if("岩质滑坡".equals(landslideShape)){
                    landslideShape = "1";
                }else if("土质滑坡".equals(landslideShape)){
                    landslideShape = "2";
                }
            }
            stratumData.get(i).setLandslideShape(landslideShape);
            String relativeRiverPosition = stratumData.get(i).getRelativeRiverPosition();
            if(PlatformObjectUtils.isNotEmpty(relativeRiverPosition)){
                if("左岸".equals(relativeRiverPosition)){
                    relativeRiverPosition = "1";
                }else if("右岸".equals(relativeRiverPosition)){
                    relativeRiverPosition = "2";
                }
            }
            stratumData.get(i).setRelativeRiverPosition(relativeRiverPosition);
            String slopeStructureType = stratumData.get(i).getSlopeStructureType();
            if(PlatformObjectUtils.isNotEmpty(slopeStructureType)){
                if("顺向斜坡".equals(slopeStructureType)){
                    slopeStructureType = "1";
                }else if("反向斜坡".equals(slopeStructureType)){
                    slopeStructureType = "2";
                }else if("切向斜坡".equals(slopeStructureType)){
                    slopeStructureType = "3";
                }else if("直立斜坡".equals(slopeStructureType)){
                    slopeStructureType = "4";
                }
            }
            stratumData.get(i).setSlopeStructureType(slopeStructureType);
            @NotNull(message = "省不能为空") String province = stratumData.get(i).getProvince();
            if(PlatformObjectUtils.isNotEmpty(province)){
                province = URLEncoder.encode(province,"UTF-8");
            }
            @NotNull(message = "市不能为空") String city = stratumData.get(i).getCity();
            if(PlatformObjectUtils.isNotEmpty(city)){
                city = URLEncoder.encode(city,"UTF-8");
            }
            @NotNull(message = "区县不能为空") String area = stratumData.get(i).getCountry();
            if(PlatformObjectUtils.isNotEmpty(area)){
                area = URLEncoder.encode(area,"UTF-8");
            }
            if(PlatformObjectUtils.isNotEmpty(province)){
                if(PlatformObjectUtils.isEmpty(city)){
                    city = "-1";
                }
                if(PlatformObjectUtils.isEmpty(area)){
                    area = "-1";
                }
                String divisionIds = sysAreaService.getIdByCondition(province, city, area);
                if(PlatformObjectUtils.isNotEmpty(divisionIds)){
                    String[] split = divisionIds.split("_");
                    if(split.length==3){
                        stratumData.get(i).setProvince(split[0]);
                        stratumData.get(i).setCity(split[1]);
                        stratumData.get(i).setCountry(split[2]);
                    }else if(split.length==2){
                        stratumData.get(i).setProvince(split[0]);
                        stratumData.get(i).setCity(split[1]);
                    }else if(split.length==1){
                        stratumData.get(i).setProvince(split[0]);
                    }
                }
            }

        }
        landslideSiteRepository.batchSave(stratumData);
    }

    private RestResponse saveShpData(ParsingResult shpData,String dataVersion) {
        try {
            if(StringUtils.isBlank(dataVersion)){
                dataVersion = IdUtil.getSnowflakeNextIdStr();
            }
            List<LandslideSiteFileData> list = getList(shpData.getShpList(), dataVersion);
            landslideSiteRepository.batchSave(list);
            ListJcVo<LandslideSiteFileData> FileData = new ListJcVo<>();
            //版本号
            FileData.setDataVersion(dataVersion);
            //是否弹窗
            FileData.setOpen("0");
            return RestResponse.succeed(FileData);
        } catch (ShpFieldException e) {
            return RestResponse.fail(e.getMessage());
        } catch (IndexOutOfBoundsException e1) {
            return RestResponse.fail("字段数量不符合要求");
        }
    }

    private List<LandslideSiteFileData> getList(List<List<Object>> shpList, String dataVersion) throws ShpFieldException {
        // 获取当前登录用户
        ArrayList<LandslideSiteFileData> arrayList = new ArrayList<>();
        for (List<Object> list : shpList) {
            arrayList.add(new LandslideSiteFileData());
        }
        return arrayList;
    }


    /**
     * 解析shp文件返回shp数据
     *
     * @param fileIds 文件ids以,分割
     * @return
     */
    public ParsingResult getShpData(String fileIds) throws Exception {
        //.prj结尾用来校验是否为2000坐标系
        String prj = "";
        //.cpg文件用来获得编码格式,例如utf-8
        String cpg = "";
        //.shp文件用来获得数据
        String shp = "";
        //根据id获取真实地址
        String[] split = fileIds.split(",");
        for (String id : split) {
            //根据id和文件名获取真实的放在磁盘上的文件
            AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(id);
            String attachPath = attachmentInfoEntity.getAttachPath();
            String substring = attachPath.substring(attachPath.length() - 4);
            if (substring.equals(".prj")) {
                prj = localDir + File.separator + attachPath;
            } else if (substring.equals(".cpg")) {
                cpg = localDir + File.separator + attachPath;
            } else if (substring.equals(".shp")) {
                shp = localDir + File.separator + attachPath;
            }
        }
        return ShpAnalyticUtil.analytic(prj, cpg, shp);
    }


    /**
     * 统一文件名
     *
     * @param fileIds
     */
    @Transactional(noRollbackFor = ShpFieldException.class)
    public void uniformFileName(String fileIds) {
        String[] idList = fileIds.split(",");
        AttachmentInfoEntity attachRoot = attachmentInfoService.getAttach(idList[0]);
        String attachRootPath = attachRoot.getAttachPath();
        String filePathCurrTime = getFilePathCurrTime(attachRootPath);
        for (int i = 1; i < idList.length; i++) {
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(idList[i]);
            if (getFilePathCurrTime(attach.getAttachPath()).equals(filePathCurrTime)) {
                continue;
            }
            String attachPath = attach.getAttachPath();
            String fileDiskPath = localDir + attachPath;
            String newName = getNonSuffixFileName(attach.getAttachName()) + "_" + filePathCurrTime + "." + FileUtil.getSuffix(attach.getAttachName());
            FileUtil.rename(new File(fileDiskPath), newName, true);
            attach.setAttachPath(attachPath.replace(getFilePathCurrTime(attachPath), filePathCurrTime));
            attachmentInfoService.update(attach);
        }
    }

    private String getFilePathCurrTime(String filePath) {
        return StringUtils.substringAfterLast(filePath, "_").replaceAll("." + FileUtil.getSuffix(StringUtils.substringAfterLast(filePath, "_")), "");
    }

    private String getNonSuffixFileName(String fileName) {
        return fileName.replaceAll("." + FileUtil.getSuffix(fileName), "");
    }

    @Override
    public Map<String, Object> dataPage(DataPageVO dataPageVO) {
        Map<String, Object> map = landslideSiteRepository.dataPage(dataPageVO);
        List<LandslideSiteFileData> list =(List<LandslideSiteFileData>) map.get("rows");
        if(PlatformObjectUtils.isNotEmpty(list)){
            for(LandslideSiteFileData entity:list){
                numberTransToString(entity);
                entity.setUploadTime(entity.getCreateTime());
                entity.setUploadUserName(entity.getCreateUserName());
            }
        }
        return map;
    }

    public void numberTransToString(LandslideSiteFileData entity){
        String landslideType = entity.getLandslideType();
        if(PlatformObjectUtils.isNotEmpty(landslideType)){
            if("1".equals(landslideType.trim())){
                landslideType = "牵引式滑坡";
            }else if("2".equals(landslideType.trim())){
                landslideType = "推移式滑坡";
            }else if("3".equals(landslideType.trim())){
                landslideType = "混合式滑坡";
            }
        }
        entity.setLandslideType(landslideType);
        String landslideShape = entity.getLandslideShape();
        if(PlatformObjectUtils.isNotEmpty(landslideShape)){
            if("1".equals(landslideShape.trim())){
                landslideShape = "岩质滑坡";
            }else if("2".equals(landslideShape.trim())){
                landslideShape = "土质滑坡";
            }
        }
        entity.setLandslideShape(landslideShape);
        String relativeRiverPosition = entity.getRelativeRiverPosition();
        if(PlatformObjectUtils.isNotEmpty(relativeRiverPosition)){
            if("1".equals(relativeRiverPosition.trim())){
                relativeRiverPosition = "左岸";
            }else if("2".equals(relativeRiverPosition.trim())){
                relativeRiverPosition = "右岸";
            }
        }
        entity.setRelativeRiverPosition(relativeRiverPosition);
        String slopeStructureType = entity.getSlopeStructureType();
        if(PlatformObjectUtils.isNotEmpty(slopeStructureType)){
            if("1".equals(slopeStructureType.trim())){
                slopeStructureType = "顺向斜坡";
            }else if("2".equals(slopeStructureType.trim())){
                slopeStructureType = "反向斜坡";
            }else if("3".equals(slopeStructureType.trim())){
                slopeStructureType = "切向斜坡";
            }else if("4".equals(slopeStructureType.trim())){
                slopeStructureType = "直立斜坡";
            }
        }
        entity.setSlopeStructureType(slopeStructureType);
        Map areaMap = JSON.parseObject((String)JSONObject.parse(stringRedisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY + "areaMap")), Map.class);
        if(areaMap==null){
            String url = BuildUrl.buildUrl() + "/sorg_dzj/getAllDivision";
            Map<String, Object> paramMap = new HashMap<>(1);
            ResponseEntity<String> responseEntity = restTemplateUtil.sendHttpRequest(url, paramMap);
            List sysAreaList = CreateGson.createGson().fromJson(responseEntity.getBody(), List.class);
            Map<String,String> tempMap = new HashMap<>();
            if(sysAreaList!=null && sysAreaList.size()>0){
                for(int i=0;i<sysAreaList.size();i++){
                    LinkedTreeMap map =(LinkedTreeMap) sysAreaList.get(i);
                    tempMap.put(map.get("uuid").toString(),map.get("name").toString());
                }
            }
            if(tempMap.size() > 0){
                redisTemplate.opsForValue().set(FxfzConstants.CACHE_SYS_KEY +  "areaMap", CreateGson.createGson().toJson(tempMap));
            }
            areaMap = tempMap;
        }
        entity.setProvince((String)areaMap.get(entity.getProvince()));
        entity.setCity((String)areaMap.get(entity.getCity()));
        entity.setCountry((String)areaMap.get(entity.getCountry()));
    }
    @Override
    public void exportExcel(HttpServletResponse response, DataPageVO dataPageVO) throws Exception{
        List<LandslideSiteFileData> list = landslideSiteRepository.getLanslideSiteFileData(dataPageVO);
        if (list == null || list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        for(LandslideSiteFileData entity:list){
            String landslideType = entity.getLandslideType();
            if(PlatformObjectUtils.isNotEmpty(landslideType)){
                landslideType =landslideType.trim();
                if("1".equals(landslideType)){
                    landslideType = "牵引式滑坡";
                }else if("2".equals(landslideType)){
                    landslideType = "推移式滑坡";
                }else if("3".equals(landslideType)){
                    landslideType = "混合式滑坡";
                }
            }
            entity.setLandslideType(landslideType);
            String landslideShape = entity.getLandslideShape();
            if(PlatformObjectUtils.isNotEmpty(landslideShape)){
                landslideShape = landslideShape.trim();
                if("1".equals(landslideShape)){
                    landslideShape = "岩质滑坡";
                }else if("2".equals(landslideShape)){
                    landslideShape = "土质滑坡";
                }
            }
            entity.setLandslideShape(landslideShape);
            String relativeRiverPosition = entity.getRelativeRiverPosition();
            if(PlatformObjectUtils.isNotEmpty(relativeRiverPosition)){
                relativeRiverPosition = relativeRiverPosition.trim();
                if("1".equals(relativeRiverPosition)){
                    relativeRiverPosition = "左岸";
                }else if("2".equals(relativeRiverPosition)){
                    relativeRiverPosition = "右岸";
                }
            }
            entity.setRelativeRiverPosition(relativeRiverPosition);
            String slopeStructureType = entity.getSlopeStructureType();
            if(PlatformObjectUtils.isNotEmpty(slopeStructureType)){
                slopeStructureType =slopeStructureType.trim();
                if("1".equals(slopeStructureType)){
                    slopeStructureType = "顺向斜坡";
                }else if("2".equals(slopeStructureType)){
                    slopeStructureType = "反向斜坡";
                }else if("3".equals(slopeStructureType)){
                    slopeStructureType = "切向斜坡";
                }else if("4".equals(slopeStructureType)){
                    slopeStructureType = "直立斜坡";
                }
            }
            entity.setSlopeStructureType(slopeStructureType);
            String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(entity.getProvince() + "," + entity.getCity() + "," + entity.getCountry());
            entity.setProvince(areaNameByAreaId.split(",")[0]);
            entity.setCity(areaNameByAreaId.split(",")[1]);
            entity.setCountry(areaNameByAreaId.split(",")[2]);
        };
        landslideSiteRepository.exportExcel(list,response);
    }

    @Override
    public List<FieldDesc>  getFieldDesc() {
        Field[] declaredFields = LandslideSiteFileData.class.getDeclaredFields();
        List<FieldDesc> list = new ArrayList<>();
        AtomicInteger sno = new AtomicInteger(1);
        if(declaredFields.length>0){
            for(Field field : declaredFields){
                FieldDesc fieldDesc = new FieldDesc();
                field.setAccessible(true);
                EntityValue entityValue = field.getAnnotation(EntityValue.class);
                if(entityValue==null){
                    continue;
                }
                String type = entityValue.type();
                String must = entityValue.must();
                String name = entityValue.name();
                String desc = entityValue.desc();
                String fieldName = field.getName();
                fieldDesc.setType(type).setMust(must).setName(name).setDesc(desc).setSno(sno.get());
                sno.getAndAdd(1);
                list.add(fieldDesc);
            }
        }
        return list;
    }

    @Override
    public Map<String, Object> pageForAnalyse(VersionPageVO param) {
        Map<String, Object> map = landslideSiteRepository.pageForAnalyse(param);
        List<LandslideSiteVersion> list =(List<LandslideSiteVersion>) map.get("rows");
        List<LandslideSiteVO> voList = new ArrayList<>(list.size());
        if(PlatformObjectUtils.isNotEmpty(list)){
            list.forEach(entity->{
                LandslideSiteVO vo = new LandslideSiteVO();
                BeanUtils.copyProperties(entity,vo);
                fileIdTransformEntity(entity,vo);
                vo.setUploadUser(entity.getUploadUserName());
                voList.add(vo);
            });
        }
        map.put("rows", voList);
        return map;
    }

    @Override
    public Map<String, Object> sameTypeDataExist(SysDataVersionSameTypeDataExistParam sysDataVersionSameTypeDataExistParam) {
        String versionCode = landslideSiteRepository.sameTypeDataExist(sysDataVersionSameTypeDataExistParam);
        boolean isExist = StringUtils.isNotBlank(versionCode);
        return new HashMap<String, Object>() {
            {
                put("isExist", isExist);
                if (isExist) {
                        put("tipMsg", "本系统已有同类滑坡数据（版本号为" + versionCode + "），是否作为新版本数据进行上传？");
                        put("versionCode", versionCode);
                }
            }
        };
    }

    @Override
    public List<String> getVersionCodeListByType(){
        return landslideSiteRepository.getVersionCodeListByType();
    }

    @Override
    public List<SlopesVO> getSlopeAreaByGeomAndVersion1(String geomText, String param2) {
        return landslideSiteRepository.getSlopeAreaByGeomAndVersion1(geomText,param2);
    }

    @Override
    public List<Map<String,Object>> getByGeomAndVersion2(String tableName, String param2) {
        return landslideSiteRepository.getByGeomAndVersion2(tableName,param2);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delDataFile(String versionCode,String fileId) {
        //获取并删除上传的文件
        List<AttachmentInfoEntity> attachmentInfoEntities = attachmentInfoService.queryFile(fileId);
        if(PlatformObjectUtils.isNotEmpty(attachmentInfoEntities)){
            //删除上传到服务器的文件
            attachmentInfoEntities.forEach(attachmentInfoEntity -> {
                File file = new File(attachmentInfoEntity.getFileDirId() + File.separator + attachmentInfoEntity.getAttachPath());
                file.deleteOnExit();
            });
        }
        //删除上传的文件数据
        landslideSiteRepository.deleteFileData(versionCode);
        //恢复之前假删的文件数据
        landslideSiteRepository.restoreFileData(versionCode);
    }

    @Override
    public void deleteFileDataWithOutVesrion() {
        //当前天的开始时间
        Date beginOfDay = DateUtil.beginOfDay(new Date());//2021-06-30 00:00:00
        //当前天的结束时间
        Date endOfDay = DateUtil.endOfDay(new Date());
        //获取文件数据表并比对版本表获取文件数据表中有版本但版本表中没版本的数据并删除（假删）
        landslideSiteRepository.timingDeleteFileData(beginOfDay,endOfDay);
    }

    @Override
    public JSONObject listForDp() throws ExecutionException, InterruptedException {
        JSONObject js = new JSONObject();
//        CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            //滑坡现场调查数据
            List<LandslideSiteFileData> list = landslideSiteRepository.listForDp();
            List<SensingImage> list2 = sensingImageRepository.getDataForDp();
            Map<String,String> codeMap = new HashMap<>();
            Map<String,BigDecimal> resultMap = new HashMap<>();
            if(PlatformObjectUtils.isNotEmpty(list) && list.size()>0){
                for (String pid : provinceCodeList()) {
                    List<LandslideSiteFileData> proList = list.stream().filter(landslideSiteFileData -> pid.equals(landslideSiteFileData.getProvince())).collect(Collectors.toList());
                    BigDecimal size = PlatformObjectUtils.isEmpty(proList)?BigDecimal.ZERO:BigDecimal.valueOf(proList.size());
                    String provinceCode = sysAreaService.getDivisionCodeById(pid);
                    provinceCode = JSONObject.parseObject(provinceCode,String.class);
                    //省名称
                    String name = sysAreaService.getAreaNameByAreaId(pid);
                    if(!codeMap.containsKey(name)){
                        codeMap.put(name,provinceCode);
                    }
                    resultMap.put(provinceCode+"_"+name,size);
                    //按市分组
                    if(PlatformObjectUtils.isNotEmpty(proList)){
                        Map<String, List<LandslideSiteFileData>> cityMap = proList.stream().collect(Collectors.groupingBy(LandslideSiteFileData::getCity));
                        cityMap.forEach((k1,v1)->{
                            String cityCode = JSONObject.parseObject(sysAreaService.getDivisionCodeById(k1),String.class);
                            String cityName = sysAreaService.getAreaNameByAreaId(k1);
                            BigDecimal citySize =  PlatformObjectUtils.isEmpty(v1)?BigDecimal.ZERO:BigDecimal.valueOf(v1.size());
                            if(!codeMap.containsKey(cityName)){
                                codeMap.put(cityName,cityCode);
                            }
                            resultMap.put(cityCode+"_"+cityName,citySize);
                        });
                    }
                }
            }
            if(PlatformObjectUtils.isNotEmpty(list2) && list2.size()>0){
                for (String pName : provinceNameList()) {
                    List<SensingImage> proList = list2.stream().filter(sensingImage -> pName.equals(sensingImage.getProvince())).collect(Collectors.toList());
                    String pCode = "";
                    if(codeMap.containsKey(pName)){
                        pCode = codeMap.get(pName);
                    }else{
                        MhjArea area = getArea(pName,"","");
                        pCode = area.getCode();
                        codeMap.put(pName,pCode);

                    }
                    BigDecimal size = PlatformObjectUtils.isEmpty(proList)?BigDecimal.ZERO:BigDecimal.valueOf(proList.size());
                    if(resultMap.containsKey(pCode+"_"+pName)){
                        BigDecimal result = resultMap.get(pCode+"_"+pName);
                        result = result.add(size);
                        resultMap.put(pCode+"_"+pName,result);
                    }else{
                        resultMap.put(pCode+"_"+pName,size);
                    }
                    //按市分组
                    if(PlatformObjectUtils.isNotEmpty(proList)){
                        String flag = "1";
                        Map<String, List<SensingImage>> cityMap = null;
                        if("北京市".equals(pName) || "上海市".equals(pName) || "天津市".equals(pName) || "重庆市".equals(pName)){
                            cityMap = proList.stream().collect(Collectors.groupingBy(SensingImage::getCountry));
                            flag = "2";
                        }else{
                            cityMap = proList.stream().collect(Collectors.groupingBy(SensingImage::getCity));
                        }
                        String finalFlag = flag;
                        try{
                            cityMap.forEach((k1, v1)->{
                                String cityCode = "";
                                if(codeMap.containsKey(k1)){
                                    cityCode = codeMap.get(k1);
                                }else{
                                    try{
                                        String province = URLEncoder.encode(pName,"UTF-8");
                                        String city =  URLEncoder.encode(k1,"UTF-8");
                                        String areaStr1 = sysAreaService.getSysAreaByName(province,city,"");
                                        if("2".equals(finalFlag)){
                                            areaStr1 = sysAreaService.getSysAreaByName(province,province,city);
                                        }
                                        MhjArea area1 = CreateGson.createGson().fromJson(areaStr1, MhjArea.class);
                                        cityCode = area1.getCode();
                                        codeMap.put(k1,cityCode);
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                                BigDecimal citySize =  PlatformObjectUtils.isEmpty(v1)?BigDecimal.ZERO:BigDecimal.valueOf(v1.size());
                                if(resultMap.containsKey(cityCode+"_"+k1)){
                                    BigDecimal result = resultMap.get(cityCode+"_"+k1);
                                    result = result.add(citySize);
                                    resultMap.put(cityCode+"_"+k1,result);
                                }else{
                                    resultMap.put(cityCode+"_"+k1,citySize);
                                }
                            });
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                }
            }
            js.put("hp",resultMap);
//            return 1;
//        }, executor);
        //CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {

            //统计所有任务钻孔点且是砂土液化的点的数量
            List<SandLiquefactionDrill> sandDrillList = sandLiquefactionRepository.getAllDrillForDp();
            Table<Double,Double,String> table = HashBasedTable.create();
            //保存各个省市的沙土液化的钻孔的数量
            Map<String,BigDecimal> sandMap = new HashMap<>();
            for (SandLiquefactionDrill sandLiquefactionDrill : sandDrillList) {
                double longitude = sandLiquefactionDrill.getLongitude().doubleValue();
                double latitude = sandLiquefactionDrill.getLatitude().doubleValue();
                if(PlatformObjectUtils.isEmpty(table.get(longitude,latitude))){
                    Map<String, String> map = LocationUtil.getGPositionByTD(longitude, latitude);
                    //省名称
                    String province = map.get("province");
                    if(StringUtils.isBlank(province)){
                        continue;
                    }
                    //省code
                    String pCode = codeMap.get(province);
                    if(StringUtils.isBlank(pCode)){
                        MhjArea area = getArea(province,"","");
                        assert area != null;
                        pCode = area.getCode();
                        codeMap.put(province,pCode);
                    }
                    if(!sandMap.containsKey(pCode+"_"+province)){
                        sandMap.put(pCode+"_"+province,BigDecimal.ONE);
                    }else{
                        BigDecimal result = sandMap.get(pCode+"_"+province);
                        result = result.add(BigDecimal.ONE);
                        sandMap.put(pCode+"_"+province,result);
                    }
                    String name = "";
                    String city = "";
                    String county = "";
                    String cCode = codeMap.get(city);
                    if("北京市".equals(province) || "上海市".equals(province) || "天津市".equals(province) || "重庆市".equals(province)){
                        city =  province;
                        county = map.get("county");
                        cCode = codeMap.get(county);
                        name = county;
                    }else{
                        city = map.get("city");
                        name = city;
                    }
                    if(StringUtils.isBlank(cCode)){
                        MhjArea area = getArea(province, city, county);
                        assert area != null;
                        cCode = area.getCode();
                        codeMap.put(name,cCode);
                    }
                    if(!sandMap.containsKey(cCode+"_"+name)){
                        sandMap.put(cCode+"_"+name,BigDecimal.ONE);
                    }else{
                        BigDecimal result = sandMap.get(cCode+"_"+name);
                        result = result.add(BigDecimal.ONE);
                        sandMap.put(cCode+"_"+name,result);
                    }
                    table.put(longitude,latitude,pCode+"_"+cCode);
                }else{
                    Map<String, String> map = codeMap.entrySet().stream().collect(Collectors.toMap(entity -> entity.getValue(), entity -> entity.getKey()));
                    String code = table.get(longitude, latitude);
                    String pCode = code.split("_")[0];
                    String cCode = code.split("_")[1];
                    String  pName = map.get(pCode);
                    if(!sandMap.containsKey(pCode+"_"+pName)){
                        sandMap.put(pCode+"_"+pName,BigDecimal.ONE);
                    }else{
                        BigDecimal result = sandMap.get(pCode+"_"+pName);
                        result = result.add(BigDecimal.ONE);
                        sandMap.put(pCode+"_"+pName,result);
                    }
                    String cName = map.get(cCode);
                    if(!sandMap.containsKey(cCode+"_"+cName)){
                        sandMap.put(cCode+"_"+cName,BigDecimal.ONE);
                    }else{
                        BigDecimal result = sandMap.get(cCode+"_"+cName);
                        result = result.add(BigDecimal.ONE);
                        sandMap.put(cCode+"_"+cName,result);
                    }
                }
            }
            js.put("sand",sandMap);
//            return 2;
//        }, executor);
        //统计所有任务钻孔点且是软土震陷的点的数量
        List<SoftSoilDrill> softSoilDrillList = softSoilRepository.getAllDrillForDp();
        //保存各个省市的沙土液化的钻孔的数量
        Map<String,BigDecimal> softMap = new HashMap<>();
        if(PlatformObjectUtils.isNotEmpty(softSoilDrillList) && softSoilDrillList.size()>0){
            Table<Double,Double,String> softTable = HashBasedTable.create();
            for (SoftSoilDrill sandLiquefactionDrill : softSoilDrillList) {
                double longitude = sandLiquefactionDrill.getLongitude().doubleValue();
                double latitude = sandLiquefactionDrill.getLatitude().doubleValue();
                if(PlatformObjectUtils.isEmpty(softTable.get(longitude,latitude))){
                    Map<String, String> map = LocationUtil.getGPositionByTD(longitude, latitude);
                    String province = map.get("province");
                    if(StringUtils.isBlank(province)){
                        continue;
                    }
                    String pCode = codeMap.get(province);
                    if(StringUtils.isBlank(pCode)){
                        MhjArea area = getArea(province,"","");
                        assert area != null;
                        pCode = area.getCode();
                        codeMap.put(province,pCode);
                    }
                    if(!softMap.containsKey(pCode+"_"+province)){
                        softMap.put(pCode+"_"+province,BigDecimal.ONE);
                    }else{
                        BigDecimal result = softMap.get(pCode+"_"+province);
                        result = result.add(BigDecimal.ONE);
                        softMap.put(pCode+"_"+province,result);
                    }
                    String name = "";
                    String city = "";
                    String county = "";
                    String cCode = codeMap.get(city);
                    if("北京市".equals(province) || "上海市".equals(province) || "天津市".equals(province) || "重庆市".equals(province)){
                        city =  province;
                        county = map.get("county");
                        cCode = codeMap.get(county);
                        name = county;
                    }else{
                        city = map.get("city");
                        name = city;
                    }
                    if(StringUtils.isBlank(cCode)){
                        MhjArea area = getArea(province,city,county);
                        assert area != null;
                        cCode = area.getCode();
                        codeMap.put(name,cCode);
                    }
                    if(!softMap.containsKey(cCode+"_"+name)){
                        softMap.put(cCode+"_"+name,BigDecimal.ONE);
                    }else{
                        BigDecimal result = softMap.get(cCode+"_"+name);
                        result = result.add(BigDecimal.ONE);
                        softMap.put(cCode+"_"+name,result);
                    }
                    softTable.put(longitude,latitude,pCode+"_"+cCode);
                }else{
                    Map<String, String> map = codeMap.entrySet().stream().collect(Collectors.toMap(entity -> entity.getValue(), entity -> entity.getKey()));
                    String code = softTable.get(longitude, latitude);
                    String pCode = code.split("_")[0];
                    String pName = map.get(pCode);
                    String cCode = code.split("_")[1];
                    String cName = map.get(cCode);
                    if(!softMap.containsKey(pCode+"_"+pName)){
                        softMap.put(pCode+"_"+pName,BigDecimal.ONE);
                    }else{
                        BigDecimal result = softMap.get(pCode+"_"+pName);
                        result = result.add(BigDecimal.ONE);
                        softMap.put(pCode+"_"+pName,result);
                    }
                    if(!softMap.containsKey(cCode+"_"+cName)){
                        softMap.put(cCode+"_"+cName,BigDecimal.ONE);
                    }else{
                        BigDecimal result = softMap.get(cCode+"_"+cName);
                        result = result.add(BigDecimal.ONE);
                        softMap.put(cCode+"_"+cName,result);
                    }
                }
            }
        }
        js.put("soft",softMap);
        //CompletableFuture.allOf(completableFuture2,completableFuture1).get();
        List<SurfaceRupture> surfaceRuptureNumOfPg = surfaceRuptureRepository.getSurfaceRuptureNumOfPg();
        Map<String,BigDecimal> surfaceMap = new HashMap<>();
        if(PlatformObjectUtils.isNotEmpty(surfaceRuptureNumOfPg) && surfaceRuptureNumOfPg.size()>0){
            for (SurfaceRupture surfaceRupture : surfaceRuptureNumOfPg) {
                //if(PlatformObjectUtils.isEmpty(surfaceTable.get(longitude,latitude))){
                    String province = surfaceRupture.getProvince();
                    if(StringUtils.isBlank(province)){
                        continue;
                    }
                    String pCode = codeMap.get(province);
                    if(StringUtils.isBlank(pCode)){
                        MhjArea area = getArea(province,"","");
                        pCode = area.getCode();
                        codeMap.put(province,pCode);
                    }
                    if(!surfaceMap.containsKey(pCode+"_"+province)){
                        surfaceMap.put(pCode+"_"+province,BigDecimal.ONE);
                    }else{
                        BigDecimal result = surfaceMap.get(pCode+"_"+province);
                        result = result.add(BigDecimal.ONE);
                        surfaceMap.put(pCode+"_"+province,result);
                    }
                    String name = "";
                    String city = "";
                    String county = "";
                    String cCode = codeMap.get(city);
                    if("北京市".equals(province) || "上海市".equals(province) || "天津市".equals(province) || "重庆市".equals(province)){
                        city =  province;
                        county = surfaceRupture.getCounty();
                        cCode = codeMap.get(county);
                        name = county;
                    }else{
                        city = surfaceRupture.getCity();
                        name = city;
                    }
                    if(StringUtils.isBlank(cCode)){
                        MhjArea area = getArea(province,city,county);
                        cCode = area.getCode();
                        codeMap.put(name,cCode);
                    }
                    if(!surfaceMap.containsKey(cCode+"_"+name)){
                        surfaceMap.put(cCode+"_"+name,BigDecimal.ONE);
                    }else{
                        BigDecimal result = surfaceMap.get(cCode+"_"+name);
                        result = result.add(BigDecimal.ONE);
                        surfaceMap.put(cCode+"_"+name,result);
                    }
//                }else{
//                    String code = surfaceTable.get(longitude, latitude);
//                    String pCode = code.split("_")[0];
//                    String cCode = code.split("_")[1];
//                    if(!surfaceMap.containsKey(pCode)){
//                        surfaceMap.put(pCode,BigDecimal.ONE);
//                    }else{
//                        BigDecimal result = surfaceMap.get(pCode);
//                        result = result.add(BigDecimal.ONE);
//                        surfaceMap.put(pCode,result);
//                    }
//                    if(!surfaceMap.containsKey(cCode)){
//                        surfaceMap.put(cCode,BigDecimal.ONE);
//                    }else{
//                        BigDecimal result = surfaceMap.get(cCode);
//                        result = result.add(BigDecimal.ONE);
//                        surfaceMap.put(cCode,result);
//                    }
//                }
            }
        }
        js.put("surface",surfaceMap);
        return js;
    }

    private MhjArea getArea(String province,String city,String county){
        try{
            province = URLEncoder.encode(province,"UTF-8");
            if(StringUtils.isNotBlank(city)){
                city = URLEncoder.encode(city,"UTF-8");
            }

            if(StringUtils.isNotBlank(county)){
                county = URLEncoder.encode(county,"UTF-8");
            }
            String areaStr = sysAreaService.getSysAreaByName(province,city,county);
            MhjArea area = CreateGson.createGson().fromJson(areaStr, MhjArea.class);
            return area;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public static List<String> provinceCodeList(){
        return Arrays.asList("7b2cfda1b2c949ea82db317e88315078",
                "20c49eb015cf48e9a45eee413578e62f",
                "769cfea464a04083853b9ab7dd3a51a0",
                "7f30cd50d510441dbfd6c4877fdeac87",
                "afcbf07008a34c2e85917cfd31238033",
                "35f88913efe7438b9b2074f12b5b18f9",
                "b0304410503c45619e605f137ef57be6",
                "8b8fcb0ec50c413a9967f9681cfbe0f8",
                "5fba31cfd5fc40c5ac89e4089dd99b08",
                "9ffa65beebd149719381dc136a23223d",
                "3e68139aaf3646e7badaf6ctaiwan000",
                "25ec5088da9f4e87818abfbc83458800",
                "5f18434d356f4e6eb068bf252f2f19ff",
                "71e49ff0bf844a30bc9cf6a139280da6",
                "8643bfae11404db8b8cf4731b1a58e1b",
                "225ac763ab714524b87d95140a923456",
                "c40625160ee6409892204e2809a78da4",
                "dce11b33497d49fca78cb2d90ac744da",
                "8a3f7d3f78ad456f92f487a979034567",
                "ccd067d35e2e46d18fb81eca404a746b",
                "ac049f6db5214260ba331f68058aab98",
                "87a6c4e106d24becb292d26eb4dc5bf4",
                "a0b7587a22604576911a6eb6d11c25d2",
                "2dc63a0f7551425283f9cee643d46f1b",
                "ff5a146797354036940586f1030fde30",
                "586da349d901406791419143ff19c8b4",
                "a1532e75535442d1bccf3a32e7841e79",
                "cd726776c7de41e4a41dcdb3d9012345",
                "8f5609fc349d45c9a56cdff3f4349d91",
                "271806e179054ec3a26e2b2b4eb4cba6",
                "706c6263fb6542cea8d4f4af7dff5f94",
                "7870ea0ad9704663b3a0dccb205ac0b2",
                "58d50e82c1184ba6969957721344a6d9");
    }

    private Map<String,String> provinceMap(){
        Map<String,String> map = new HashMap<>();
        map.put("320000","江苏省");
        map.put("510000","四川省");
        map.put("660000","新疆生产建设兵团");
        map.put("340000","安徽省");
        map.put("500000","重庆市");
        map.put("440000","广东省");
        map.put("630000","青海省");
        map.put("350000","福建省");
        map.put("230000","黑龙江省");
        map.put("330000","浙江省");
        map.put("710000","台湾省");
        map.put("610000","陕西省");
        map.put("150000","内蒙古自治区");
        map.put("220000","吉林省");
        map.put("360000","江西省");
        map.put("120000","天津市");
        map.put("210000","辽宁省");
        map.put("370000","山东省");
        map.put("310000","上海市");
        map.put("640000","宁夏回族自治区");
        map.put("430000","湖南省");
        map.put("450000","广西壮族自治区");
        map.put("620000","甘肃省");
        map.put("140000","山西省");
        map.put("540000","西藏自治区");
        map.put("530000","云南省");
        map.put("130000","河北省");
        map.put("110000","北京市");
        map.put("460000","海南省");
        map.put("420000","湖北省");
        map.put("520000","	贵州省");
        map.put("410000","河南省");
        map.put("650000","新疆维吾尔自治区");
        return map;
    }
    public static List<String> provinceNameList(){
        return Arrays.asList("江苏省",
                "四川省" ,
                "新疆生产建设兵团" ,
                "安徽省",
                "重庆市",
                "广东省" ,
                "青海省" ,
                "福建省" ,
                "黑龙江省" ,
                "浙江省" ,
                "台湾省" ,
                "陕西省" ,
                "内蒙古自治区" ,
                "吉林省" ,
                "江西省" ,
                "天津市" ,
                "辽宁省" ,
                "山东省" ,
                "上海市" ,
                "宁夏回族自治区" ,
                "湖南省" ,
                "广西壮族自治区" ,
                "甘肃省" ,
                "山西省" ,
                "西藏自治区" ,
                "云南省" ,
                "河北省" ,
                "北京市" ,
                "海南省" ,
                "湖北省" ,
                "贵州省" ,
                "河南省" ,
                "新疆维吾尔自治区");
    }
}
